/*
  通过axios请求web api
*/
import http from "./http.js"
import { mockPhone, mockDate } from '@/utils/common.js'
import { tryParseBool } from '@/utils/common'


// 从环境变量配置文件获取配置:是否使用模拟数据(bool)
let appMock = tryParseBool(process.env.VUE_APP_MOCK)
let nodeEnv = process.env.NODE_ENV
// 生成图片背景色
const imageColor = '#894FC4'

const Mock = require("mockjs")
if (appMock === undefined) {
  appMock = false
} else if (appMock === true) {
  console.log('init mock')
}

export const _randomImageColor = function () {
  let colors = {
    "--el-color-white": "#ffffff",
    "--el-color-black": "#000000",
    "--el-color-primary": " #409eff",
    "--el-color-primary-rgb": "64,158,255",
    "--el-color-success-rgb": "103,194,58",
    "--el-color-warning-rgb": "230,162,60",
    "--el-color-danger-rgb": "245,108,108",
    "--el-color-error-rgb": "245,108,108",
    "--el-color-info-rgb": "144,147,153",
    "--el-color-primary-light-1": "#53a8ff",
    "--el-color-primary-light-2": "#66b1ff",
    "--el-color-primary-light-3": "#79bbff",
    "--el-color-primary-light-4": "#8cc5ff",
    "--el-color-primary-light-5": "#a0cfff",
    "--el-color-primary-light-6": "#b3d8ff",
    "--el-color-primary-light-7": "#c6e2ff",
    "--el-color-primary-light-8": "#d9ecff",
    "--el-color-primary-light-9": "#ecf5ff",
    "--el-color-primary-dark-2": "#337ecc",
    "--el-color-success": "#67c23a",
    "--el-color-success-light-3": "#95d475",
    "--el-color-success-light-5": "#b3e19d",
    "--el-color-success-light-7": "#d1edc4",
    "--el-color-success-light-8": "#e1f3d8",
    "--el-color-success-light-9": "#f0f9eb",
    "--el-color-success-dark-2": "#529b2e",
    "--el-color-warning": "#e6a23c",
    "--el-color-warning-light-3": "#eebe77",
    "--el-color-warning-light-5": "#f3d19e",
    "--el-color-warning-light-7": "#f8e3c5",
    "--el-color-warning-light-8": "#faecd8",
    "--el-color-warning-light-9": "#fdf6ec",
    "--el-color-warning-dark-2": "#b88230",
    "--el-color-danger": "#f56c6c",
    "--el-color-danger-light-3": "#f89898",
    "--el-color-danger-light-5": "#fab6b6",
    "--el-color-danger-light-7": "#fcd3d3",
    "--el-color-danger-light-8": "#fde2e2",
    "--el-color-danger-light-9": "#fef0f0",
    "--el-color-danger-dark-2": "#c45656",
    "--el-color-error": "#f56c6c",
    "--el-color-error-light-3": "#f89898",
    "--el-color-error-light-5": "#fab6b6",
    "--el-color-error-light-7": "#fcd3d3",
    "--el-color-error-light-8": "#fde2e2",
    "--el-color-error-light-9": "#fef0f0",
    "--el-color-error-dark-2": "#c45656",
    "--el-color-info": "#909399",
    "--el-color-info-light-3": "#b1b3b8",
    "--el-color-info-light-5": "#c8c9cc",
  }

  let index = Mock.Random.integer(0, Object.keys(colors).length - 1)
  
  let color = colors[Object.keys(colors)[index]]
  // console.log(color)
  return color
}

// && process.env.NODE_ENV === "development"

//  import {request,get,post} from  "axios"

// async function getUserByUid(uid){
//     return await request({
//         method":"'get',
//         url:'/sfdsdfs?uid=' + uid
//     })
// }

// async function postXXX(params)
// {
//     return await request({
//         method:'post',
//         url:'/skjsfd',
//         data:params
//     })
// }

// async function postTestApi(params)
// {
//     return await request({
//         method:'post',
//         url:'/post-test',
//         data:params
//     })
// }

// export async function login(username, password) {
//   if (appMock) {
//     let mockData = {}
//     return mockData
//   } else {
//     return await http.request({
//       method: "POST",
//       url: "/api/login",
//       data: {
//         username,
//         password,
//       }
//     })
//   }
// }
//
// export async function logout() {
//   if (appMock) {
//     let mockData = {}
//     return mockData
//   } else {
//     return await http.request({
//       method: "GET",
//       url: "/api/logout",
//     })
//   }
// }

export async function registerApi(params) {
  if (appMock) {
    let mockData = {}
    return mockData
  } else {
    return await http.request({
      method: "POST",
      url: "/api/register",
      data: params,
    })
  }
}

export async function postUserInfo() { }
export async function getCities() { }
export async function getRegions() { }
export async function getProvince() { }
export async function getSysConfig() { }

export async function getTopicList() { }


function _mockQuestion() {
  let item = {
    img: Mock.Random.image('200x200', imageColor),
    title: Mock.Random.ctitle(6, 15),
    description: Mock.Random.ctitle(25, 50),
    answerCount: Mock.Random.integer(0, 999),
    remarkCount: Mock.Random.integer(0, 999),
    remarkStatus: Mock.Random.integer(0, 1),
    visitCount: Mock.Random.integer(100, 10000),
    date: mockDate()
    // Mock.Random.date()
  }
  return item
}

export async function getQuestionListApi(params) {
  if (appMock) {
    const maxPageIndex = 3
    let data = {
      count: maxPageIndex * params.pageSize,
      rows: []
    }

    if (params.pageIndex <= maxPageIndex) {
      for (let i = 0; i < params.pageSize; i++) {
        data.rows.push(_mockQuestion())

      }
    }

    let mockData = {
      code: 200,
      msg: 'ok',
      data: data
    }
    debugger
    return mockData
  }
  else {
    return http.request({
      method: 'GET',
      url: '/api/question/list',
      data: params
    })
  }

}


// 获取问题详情
export async function getQuestionApi(id) {
  if (appMock) {
    let mockData = {
      code: 200,
      msg: 'ok',
      data: _mockQuestion()
    }
    return mockData
  }
  else {
    return await http.request({
      method: 'GET',
      url: '/api/question?id=' + id
    })
  }

}

const _mockAnswer = function (marker) {
  
  let item = {
    id: Mock.Random.id(),
    questionId: Mock.Random.id(),
    username: Mock.Random.cname(),
    avatar: Mock.Random.image('200x200', imageColor),
    content: marker ? marker : Mock.Random.ctitle(100, 999),
    date: mockDate(3),
    commentCount: Mock.Random.integer(99, 111),
    remarkCount: Mock.Random.integer(99, 111),
    remarkStatus: Mock.Random.integer(0, 1)
  }
  return item
}
export async function getAnswerListApi(params) {
  if (appMock) {
    const maxPageIndex = 3
    let mockData = {
      code: 200,
      msg: 'ok',
      data: {
        rows: [],
        count: params.pageSize * maxPageIndex
      }
    }

    if (params.pageIndex <= maxPageIndex) {
      console.log(params.pageSize)
      for (let i = 0; i < params.pageSize; i++) {
        mockData.data.rows.push(_mockAnswer())
      }
    }

    return mockData
  }
  else {
    return await http.request({
      method: "GET",
      url: '/api/answer/list',
      data: params
    })
  }
}
export async function postAnswerApi(params) {
  if (appMock) {
    let mockDataResult =  {
      code: 200,
      msg: 'ok',
      data: _mockAnswer(params.content)
    }

    mockDataResult.data.date = new Date()
    return mockDataResult
  }
  else {
    return await http.request({
      method: 'POST',
      url: '/api/answer/post',
      data: params
    })
  }
}

export async function fetchUserApi(token){
  if(appMock){
    let mockDataResult =  {
      code: 200,
      msg: 'ok',
      data: {
        user:_mockUser(token),
        token:token
      }
    }

    return mockDataResult
  }
  else{
    return await http.request({
      method: 'POST',
      url: '/api/fetch-user',
      data: {token:token}
    })
  }
}

export async function loginApi(params){
  if(appMock){
    let mockDataResult =  {
      code: 200,
      msg: 'ok',
      data: {
        user:_mockUser(params),
        token:Mock.Random.id()
      }
    }
    return mockDataResult
  }
  else{
    return await http.request({
      method: 'POST',
      url: '/api/login',
      data: params
    })
  }
}

const _mockUser = function (params){
  let mockUser = {
    username: '测试',
    nickname:'测试',
    avatar:'/user/120381830219380913/avatar.png'
  }
  return mockUser
}

const _mockComment = function (marker) {
  let item = {
    id: Mock.Random.id(),
    uid: Mock.Random.id(),
    name: Mock.Random.cname(),
    avatar: Mock.Random.image('200x200', imageColor),
    referenceUid: Mock.Random.id(),
    referenceName: Mock.Random.cname(),
    questionId: Mock.Random.id(),
    answerId: Mock.Random.id(),
    date: mockDate(3),
    content: marker ? marker : Mock.Random.ctitle(15, 150),
    favoriteCount: Mock.Random.integer(999, 9999),
    favoriteStatus: Mock.Random.integer(0, 1)
  }
  return item
}
export async function getCommentListApi(params) {
  if (appMock) {
    const maxPageIndex = 3
    let mockData = {
      code: 200,
      msg: 'ok',
      data: {
        rows: [],
        count: maxPageIndex * params.pageSize
      }
    }

    if (params.pageIndex <= maxPageIndex) {
      for (let i = 0; i < params.pageSize; i++) {

        mockData.data.rows.push(_mockComment())
      }
    }
    return mockData
  }
  else {
    return await http.request({
      method: 'GET',
      url: '/api/comment/list',
      data: params
    })
  }
}
export async function postCommentApi(params) {
  if (appMock) {
    let mockData = {
      code: 200,
      msg: 'ok',
      data: _mockComment(params.content)
    }

    // mockData.data = Object.assign({}, params)
    // mockData.data.name = Mock.Random.cname()
    // mockData.data.date = mockDate()
    // mockData.data.uid = Mock.Random.id()
    // mockData.data.favoriteCount = 0
    // mockData.data.favoriteStatus = 0
    mockData.data.date = new Date()

    return mockData
  }
  else {
    await http.request({
      url: '/api/comment/save',
      method: 'POST',
      data: params
    })
  }
}

export async function getRequirementByIdApi(id) {
  if (appMock) {
    let imgs = []
    for (let i = 0; i < 8; i++) {
      imgs.push(Mock.Random.image('800x600', imageColor))
    }
    let data = {
      imgs: imgs,
      title: Mock.Random.ctitle(6, 15),
      price: "面议",
      types: "",
      publisherPhone: mockPhone(),
      publisherUid: Mock.Random.id(),
      publisherName: Mock.Random.cname(),
      publishDate: Mock.Random.date(),
      content: '紫金花实体店手机电脑平板笔记本耳机智能手表单反相机回收抵押置换:苹果,华为,OPPO,vivo，小米,三星，魅族，一加，威图.全新，充新，二手等品牌手机电脑数码产品。<br />正规实体店专业高价回收手机，以多年的经验、专业的水平，常年大量回收高，中档手机，上门回收，我们以高价位，高质量的服务深得广大客户好评，以真诚地态度、真正的价格，精诚，合作共赢！！！<br /><br />全市区高价上门回收以下各品牌手机:<br />1、苹果手机回收：iphone13全系列5G手机，iPhone12全系列5G手机，iphone11全系列手机,iPhoneX全系列、iPhone8、iPhone7、iPhone6、iPhoneSE2，等苹果全系列<br /><br />2:三星手机回收:W全系列S全系列，A全系列note全系列折叠屏全系列M全系列<br /><br />3华为手机手机回收:华为mate40全系列，华为P50全系列，华为P40全系列，华为P30全系列,华为mate30全系列,华为mate20全系列、华为P20全系列，华为5G全系列，华为保时捷全系列，华为Nova全系列，华为荣耀全系列，华为畅享全系列。<br /><br />4:OPPO手机回收:OPPOReno6Pro5G，Reno全系列，FindX全系列，K全系列，A全系列，R全系列OPPOR17，r15，K9，K7，A95，X50、Q3，A72，A93，等全系。<br /><br />5；vivo手机回收:vivoX60全系列，Y全系列，S全系列，IQOO5G全系列，vivoX50Pro5G,X305G，X27，X23、NEX3、IQOO7，IQOO5，IQOO3，S10，S9，S7，y53，y70，y73等全系列。<br />6小米手机回收小米11全系列，小米10全系列，小米9全系列，红米手机全系列。<br /><br />7平板系列：苹果iPad、华为平板，三星平板、微软平板、小米平板、E人E本等。<br /><br />8笔记本系列：苹果笔记本、外星人笔记本、联想笔记本、戴尔笔记本、华硕笔记本等品牌。<br /><br />9台式电脑系列：苹果电脑、外星人电脑、戴尔电脑、联想电脑、惠普电脑、组装电脑等。<br /><br />10一体电脑系列：苹果一体机、戴尔一体机、联想一体机、惠普一体机<br />诚实守信，&nbsp;价格合理，&nbsp;合法经营，欢迎新老客户咨询！！！节假日不休息！！！<br /><br />特别提醒：本店拒收偷盗抢劫等来路不明的机器！！！！！！<br />联系我时，请说是在58同城看到的，谢谢！<br />您在接受平台商家提供的服务前，注意核对商家的身份并提前确认商家提供的产品/服务是否符合相关法律规定。联系我时，请说是在58同城看到的，谢谢！',
    }
    return {
      code: 200,
      msg: 'ok',
      data: data
    }
  } else {
    return await http.request({
      method: "GET",
      url: "/api/get-requirement?id=" + id,
    })
  }
}

export async function postRequirementApi(params) {
  if (appMock) {
    return
  } else {
    return await http.request({
      method: "POST",
      url: "/api/post-requirement",
      data: params,
    })
  }
}

const _mockMsg = function (i) {
  let item = {
    id:Mock.Random.id(),
    avatar: Mock.Random.image('200x200', _randomImageColor()),
    name: Mock.Random.cname(),
    uid: Mock.Random.id(),
    isSelf: Mock.Random.integer(0, 1),
    isPicture: Mock.Random.integer(0, 1),
    content: i + ' ' + Mock.Random.ctitle(10, 100),
    picture: Mock.Random.image( Mock.Random.integer(1,5) * 100 +'x'+Mock.Random.integer(1,5) * 100,_randomImageColor()),
    date: mockDate()
  }
  return item
}
// const _mockMsgList = function(){
//   let msgList = {
//     avatar: Mock.Random.image('200x200', _randomImageColor()),
//     name: Mock.Random.cname(),
//     uid: Mock.Random.id(), 
//     list:[]
//   }

//   for(let i=0;i<10;i++)
//   {
//      let item = {

//      }
//   }

//   return msgList 
// }

export async function getMsgListApi(params) {
  if (appMock) {

    const maxPageIndex = 3
    let mockData = {
      code: 200,
      msg: 'ok',
      data: {
        rows: [],
        count: maxPageIndex * params.pageSize
      }
    }


    if (params.pageIndex <= maxPageIndex) {
      for (let i = 0; i < params.pageSize; i++) {
        mockData.data.rows.push(_mockMsg(i))
      }
    }

    return mockData
  }
  else {
    return await http.request({
      method: 'GET',
      url: '/api/msg/list',
      data: params
    })
  }
}
export async function sendMsgApi(params) {
  if (appMock) {
    return {
      code: 200,
      msg: 'ok',
      data: _mockMsg(0)
    }
  }
  else {
    return await http.request({
      method: 'GET',
      url: '/api/msg/send',
      data: params
    })
  }
}
export async function receiveMsg() { }


export async function getSessionListApi(params) {
  if (appMock) {
    const maxPageIndex = 3
    let mockData = {
      code: 200,
      msg: 'ok',
      data: {
        rows: [],
        count: maxPageIndex * params.pageSize
      }
    }


    if (params.pageIndex <= maxPageIndex) {
      for (let i = 0; i < params.pageSize; i++) {
        let item = {
          sessionId: Mock.Random.id(),
          avatar: Mock.Random.image('200x200', _randomImageColor()),
          name: Mock.Random.cname(),
          uid: Mock.Random.id(),
          date: mockDate(),
          lastMsg: Mock.Random.ctitle(5, 25)
        }

        mockData.data.rows.push(item)
      }
    }

    return mockData
  }
  else {
    return await http.request({
      method: 'GET',
      url: '/api/session/list',
      data: params
    })
  }
}
export async function getSession() { }
export async function deleteSession() { }


const mackMockRequirementList = function (params) {
  const maxPageIndex = 2
  let mockRows = []
  if (params.pageIndex <= maxPageIndex) {
    for (let i = 0; i < params.pageSize; i++) {
      let o = {
        title: Mock.Random.ctitle(6, 15),
        city: Mock.Random.city(),
        lat: Mock.Random.integer(23, 26) + Mock.Random.float(0.0000001, 0.1),
        lng: Mock.Random.integer(120, 130) + Mock.Random.float(0.0000001, 0.1),
        price: "面议",
        date: mockDate(),
        img: Mock.Random.image('240x180', imageColor),
      }
      mockRows.push(o)
    }
  }

  let mockData = {
    code: 200,
    msg: 'ok',
    data: {
      rows: mockRows,
      count: maxPageIndex * params.pageSize
    }
  }
  return mockData
}

export async function getRequirementListApi(params) {
  if (appMock) {
    console.log(params)
    return mackMockRequirementList(params)

  } else {
    return await http.request({
      method: "GET",
      url: "/api/get-requirement-list",
      data: params
    })
  }
}

export async function getHouseListApi() {
  if (appMock) {
    let mockData = {
      code: 200,
      msg: 'ok',
      data: []
    }

    let mockCount = 2
    let mockDataList = [];
    (function (mockCount) {

      for (let i = 0; i < mockCount; i++) {
        let address = ''
        let addressArr = []
        do {
          address = Mock.Random.county(true)
          addressArr = address.split(' ')
          if (address.indexOf('-') < 0 && addressArr.length >= 3) {
            break;
          }
        }
        while (true)
        let province = addressArr[0]
        let city = addressArr[1]
        let county = addressArr[2]

        // Mock.Random.county().split(' ')

        const directionArr = ['东', '西', '南', '北']

        let genTags = [];
        (function () {
          const tags = ['精装修', '有阳台', '安选', '广告', '配套齐全', '邻地铁', 'wifi', '油烟机', '冰箱', '洗衣机', '热水器']
          let tagsCount = Mock.Random.integer(1, tags.length)
          let i = 1
          while (i <= tagsCount) {
            do {
              let n = Mock.Random.integer(0, tags.length - 1)
              let tag = tags[n]
              if (genTags.indexOf(tag) < 0) {
                genTags.push(tag)
                i++
                break
              }
            }
            while (true)
          }
        })()

        let price = '';
        (function () {
          let p1 = Mock.Random.integer(8, 11)
          let p2 = Mock.Random.integer(p1 + 3, p1 * 2)
          price = p1 * 100 + '-' + p2 * 100 + '元/月'
        })()

        let o = {
          "id": Mock.Random.id(),
          "title": Mock.Random.cparagraph(3, 6),
          "username": Mock.Random.cname(),
          "direction": directionArr[Mock.Random.integer(0, 3)],
          "type": '一室一厅一卫',
          "tags": genTags,
          "price": price,
          "thumb_img": Mock.Random.image('240x180', imageColor),
          "area": Mock.Random.integer(15, 55) + '㎡',
          "address": address,
          "date": Mock.Random.date(),
          "province": province,
          "city": city,
          "county": county
        }

        mockDataList.push(o)
      }

    })(mockCount)




    return mockData
  } else {
    return await http.request({
      method: "get",
      url: "/api/get-house-list",
    })
  }
}

export async function getHouseByIdApi(id) {
  if (appMock) {
    let mockData = {}
    return mockData
  } else {
    return await http.request({
      method: "get",
      url: "/api/get-house?id=" + id,
    })
  }
}

export async function getTestApi() {
  if (appMock) {
    let mockData = {
      code: 200,
      msg: "ok",
      data: [1, 2, 3, 4, 5, 6],
    }
    return mockData
  } else {
    return await http.request({
      method: "get",
      url: "/a",
      // url:'/get-test'
    })
  }
}


